package org.example.everyday;

/**
 * <p>
 * Description:TODO 详细描述
 * <p>
 * <p>
 *
 * @author anlu
 * @date 2022/7/3 0003 12:35
 */
public class Lc556 {
    public static void main(String[] args) {
        Lc556 lc556 = new Lc556();
        int res =  lc556.nextGreaterElement(3142);
        System.out.println(res);
    }
    public int nextGreaterElement(int n) {
        char[] nums = Integer.toString(n).toCharArray();
        int i = nums.length - 2;
        while (i >= 0 && nums[i] >= nums[i + 1]){
            i--;
        }
        if(i < 0){
            return -1;
        }
        int j = nums.length - 1;
        while (j >= 0 && nums[i] >= nums[j]){
            j--;
        }
        swap(nums,i, j);
        reverse(nums,i + 1);
        long ans = Long.parseLong(new String(nums));
        return ans > Integer.MAX_VALUE ? -1 : (int)ans;
    }

    public void reverse(char[] nums,int begin){
        int i = begin, j = nums.length - 1;
        while (i < j){
            swap(nums,i , j);
            i++;
            j--;
        }
    }

    public void swap(char[] nums, int i, int j) {
        char temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }


}
